package com.zmx.common.common.config.shardingsphere;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;

/**
 * @Description: 按照时间分表
 * @ClassName: TableByDateShardingAlgorithm
 * @Author zhaomxr
 * @Date 2021-12-13 14:02
 */
@Slf4j
public abstract class TableByDateShardingAlgorithm {

    private final static String SEPARATOR = "_";

    public static String getTable(Collection<String> availableTargetNames, PreciseShardingValue<Date> preciseShardingValue, ShardingDateTypeEnum shardingDateTypeEnum) {
        // 真实数据库节点
        availableTargetNames.stream().forEach((item) -> {
            System.out.println("actual db:" + item);
        });

        // 逻辑表以及分片的字段名
        log.info("logicTable:" + preciseShardingValue.getLogicTableName() + ";shardingColumn:" + preciseShardingValue.getColumnName());
        // 分片数据字段值
        log.info("shardingColumn value:" + preciseShardingValue.getValue().toString());

        String tb_name = buildTableName(preciseShardingValue, shardingDateTypeEnum);

        // 实际的表名
        log.info("实际的表名 tb_name:" + tb_name);
        for (String each : availableTargetNames) {
            if (each.equals(tb_name)) {
                return each;
            }
        }
        throw new IllegalArgumentException();
    }

    /**
     * 构建表明真正的表明
     *
     * @param preciseShardingValue
     * @param shardingDateTypeEnum
     * @return
     */
    private static String buildTableName(PreciseShardingValue<Date> preciseShardingValue, ShardingDateTypeEnum shardingDateTypeEnum) {
        // 根据日期分表
        Date date = preciseShardingValue.getValue();
        // 取出 年、月、日
        String year = String.format("%tY", date);
        String mon = String.valueOf(Integer.parseInt(String.format("%tm", date)));
        String day = String.format("%td", date);

        // 表名前缀
        StringBuilder tb_name = new StringBuilder(preciseShardingValue.getLogicTableName());
        tb_name.append(SEPARATOR);

        switch (shardingDateTypeEnum) {
            case YEAR:
                tb_name.append(year);
                break;
            case YEAR_MOBTH:
                tb_name.append(year).append(SEPARATOR).append(mon);
                break;
            case YEAR_MOBTH_DAY:
                tb_name.append(year).append(SEPARATOR).append(mon).append(SEPARATOR).append(day);
                break;
        }

        return tb_name.toString();
    }
}
